import datetime

from django.contrib.contenttypes.models import ContentType
from django.utils import timezone

from . import models

class Action(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='actions', db_index=True)
    verb = models.CharField(max_length=255)
    created = models.DateTimeField(auto_now_add=True)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()

    class Meta:

        pass


def create_action(user, verb, target=None):

    now = timezone.now()
    last_minute = now - datetime.timedelta(seconds=60)
    similar_actions = models.Action.objects.filter(user_id=user.id, verb=verb, created_gte=last_minute)

    if target:

        target_ct = ContentType.objects.get_for_model(target)
        similiar_actions = similiar_actions.filter(content_type=target_ct, target_id=target.id)

    if not similar_actions:

        action = models.Action(user=user, verb=verb, target=target)
        action.save()

        return True

    return False
